import { isNil, map, merge, round } from 'lodash-es';
import dayjs from 'dayjs';
import { useRequest } from '@/hooks/requestHooks.js';
import { useWatch } from '@/hooks/useWatch.js';
import { basicLineXAxis, basicLineYAxis, basicLineLegend } from '@/components/chart/options/baseOptions.js';
import { getAreaList } from '@/api/index.js';
import { Message } from 'element-ui';
import { getCEQuota } from '@/api/index.js';

const commonFieldList = [
  {
    label: '1月份',
    value: 'month1',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '2月份',
    value: 'month2',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '3月份',
    value: 'month3',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '4月份',
    value: 'month4',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '5月份',
    value: 'month5',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '6月份',
    value: 'month6',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '7月份',
    value: 'month7',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '8月份',
    value: 'month8',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '9月份',
    value: 'month9',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '10月份',
    value: 'month10',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '11月份',
    value: 'month11',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
  {
    label: '12月份',
    value: 'month12',
    type: 'input',
    comp: 'el-input',
    append: 'tco2',
    placeholder: '请输入',
    bind: {
      type: 'number',
      min: 0,
      step: 0.01,
    },
  },
];
const commonRule = [{ required: true, message: '请输入', trigger: 'blur' }];
export const useQuotaRead = () => {
  const TFormQuotaRead = ref(null);
  const formOpts = reactive({
    ref: null,
    labelWidth: '70px',
    formData: {
      year: dayjs().subtract(1, 'year').format('YYYY'),
      month1: null,
      month2: null,
      month3: null,
      month4: null,
      month5: null,
      month6: null,
      month7: null,
      month8: null,
      month9: null,
      month10: null,
      month11: null,
      month12: null,
    },
    fieldList: [
      {
        label: '年份',
        value: 'year',
        comp: 'el-date-picker',
        eventHandle: {
          change: val => run({ year: val }),
        },
        bind: {
          clearable: false,
          'value-format': 'YYYY',
          type: 'year',
          'disabled-date': time => {
            return dayjs(time.getTime()) > dayjs();
          },
        },
      },
      // ...map(commonFieldList, v => ({ ...pick(v, ['label', 'value']), slotName: v.value })),
    ],
  });
  const total = ref('-');

  const openRun = () => {
    run({ year: formOpts.formData.year });
  };
  const [, , run] = useRequest(getCEQuota, {
    manual: true,
    onSuccess: res => {
      formOpts.formData = omit(res.data, ['total']);
      total.value = res.data.total;
    },
  });

  return [TFormQuotaRead, formOpts, total, openRun];
};
const lineOption = {
  dataset: {
    dimensions: [
      'date',
      { name: 'thisValue', displayName: '能耗' },
      { name: 'togetherValue', displayName: '同比' },
      { name: 'chainValue', displayName: '环比' },
    ],
    source: [],
  },
  series: Array.from({ length: 3 }, (_, idx) => {
    return idx === 0
      ? { type: 'bar', barMaxWidth: 25, yAxisIndex: 0 }
      : { type: 'line', smooth: true, showSymbol: false, yAxisIndex: 1 };
  }),
  legend: { y: 0 },
  color: ['#4992ff', '#5afe5d', '#eda422'],
  yAxis: [{ name: '' }, merge({}, basicLineYAxis, { name: '单位：%', nameTextStyle: { align: 'right' } })],
};
const pieOption = {
  tooltip: {
    trigger: 'item',
    formatter: '占比: {d}%<br />{b}: {c}',
  },
  legend: {
    show: true,
    orient: 'vertical',
    right: '20%',
    top: 'center',
    itemWidth: 10,
    itemHeight: 10,
    itemStyle: { borderWidth: 0 },
  },
  series: [
    {
      name: '',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['40%', '50%'],
      // itemStyle: {
      //   borderRadius: 10,
      //   borderColor: '#fff',
      //   borderWidth: 2,
      // },
      label: { show: false, position: 'center' },
      emphasis: {
        label: { disabled: true },
      },
      labelLine: { show: false },
      data: [{ name: '', value: '' }],
    },
  ],
};

export const barSeriesItem = {
  type: 'bar',
  showSymbol: false,
  smooth: true,
  barWidth: 12,
};
export const lineSeriesItem = {
  type: 'line',
  smooth: true,
  showSymbol: false,
};

// 统计数据小数位数保留
export const formatNumber = (num, defaultValue = '--') => {
  return isNil(num) ? defaultValue : round(num, 2);
};

// line-chart hooks
export const useCEMLineChart = (request, entId, chartRef, unit) => {
  const params = ref({
    companyId: entId.value,
    ...chartRef.value?.dateParams,
  });
  const extraOpts = ref({});
  const [data, loading, run] = useRequest(request, {
    defaultParams: [params.value],
    manual: true,
  });
  useWatch([entId, chartRef], ([n1, n2]) => {
    if (n1 && n2) {
      params.value = { companyId: n1, ...n2.dateParams };
      if (params.value.startTime && params.value.endTime) {
        run(params.value);
      } else {
        extraOpts.value.dataset.source = [];
        Message.warning('请选择开始时间和结束时间');
      }
    }
  });
  useWatch(data, n => {
    const source = map(n, v => ({
      chainValue: formatNumber(v.chainValue, null),
      date: v.date,
      thisValue: formatNumber(v.thisValue, null),
      togetherValue: formatNumber(v.togetherValue, null),
    }));
    extraOpts.value = merge({}, lineOption, { dataset: { source }, yAxis: [{ name: `单位：${unit}` }] });
  });

  return [extraOpts, loading, run];
};
// pie-chart hooks
export const useCEMPieChart = (request, entId, chartRef, unit) => {
  const params = ref({
    companyId: entId.value,
    ...chartRef.value?.dateParams,
  });
  const extraOpts = ref({});
  const [data, loading, run] = useRequest(request, {
    defaultParams: [params.value],
    manual: true,
  });
  useWatch([entId, chartRef], ([n1, n2]) => {
    if (n1 && n2) {
      params.value = { companyId: n1, ...n2.dateParams };
      run(params.value);
    }
  });
  useWatch(data, n => {
    extraOpts.value = merge({}, pieOption, {
      series: [{ data: map(n, v => ({ name: `${v.useType} (${unit})`, value: round(v.dataValue, 2) })) }],
    });
  });

  return [extraOpts, loading, run];
};
// dataPick的option
export const usePickerOption = type => {
  let choiceDate = ref(null);
  const pbObj = ref({
    onPick: ({ maxDate, minDate }) => {
      choiceDate.value = maxDate ? '' : dayjs(minDate);
    },
    disabledDate: time => {
      if (choiceDate.value) {
        const minTime = type === 'd' ? choiceDate.value.subtract(30, 'day') : choiceDate.value.subtract(5, 'month');
        const maxTime = type === 'd' ? choiceDate.value.add(30, 'day') : choiceDate.value.add(5, 'month');
        return dayjs(time) < minTime || dayjs(time) > maxTime;
      }
    },
  });
  return pbObj;
};
// 区域选择/机构选择联动
export const useCascaderLink = fn => {
  const cascader = ref();
  const cascaderProps = ref({
    emitPath: true,
    checkStrictly: true,
    label: 'areaName',
    value: 'areaName',
  });
  const [areaList] = useRequest(getAreaList, {
    defaultParams: ['山西省'],
    onSuccess: res => {
      cascader.value = '山西省';
    },
  });
  const cascaderChange = bool => {
    if (!bool) {
      fn();
    }
  };

  return [cascader, cascaderProps, areaList, cascaderChange];
};
// 能源类型展示
export const engTypeObj = {
  AIR: '气',
  ELECTRICITY: '电',
  WARM: '暖',
  WATER: '水',
};
export const engTypes = [
  { value: 'ALL', label: '总', unit: 'tce' },
  { value: 'ELECTRICITY', label: '电', unit: 'KWh' },
  { value: 'WATER', label: '水', unit: 't' },
  { value: 'AIR', label: '气', unit: 'm³' },
  { value: 'WARM', label: '暖', unit: 'KJ' },
];
export const engTypeUnit = {
  ALL: 'tce',
  ELECTRICITY: 'KWh',
  WATER: 't',
  AIR: 'm³',
  WARM: 'KJ',
};
export const engTypeDisplay = engType => {
  const engTypeArr = engType?.split('、');
  if (engTypeArr?.length > 0) {
    return engTypeArr.map(v => engTypeObj[v]).join('、');
  }
  return '--';
};
export const useQuotaInsert = () => {
  const TFormQuota = ref(null);
  const formOpts = reactive({
    ref: null,
    labelWidth: '70px',
    formData: {
      year: dayjs().format('YYYY'),
      month1: null,
      month2: null,
      month3: null,
      month4: null,
      month5: null,
      month6: null,
      month7: null,
      month8: null,
      month9: null,
      month10: null,
      month11: null,
      month12: null,
    },
    fieldList: [
      {
        label: '年份',
        value: 'year',
        comp: 'el-date-picker',
        eventHandle: {
          change: val => run({ year: val }),
        },
        bind: {
          clearable: false,
          'value-format': 'YYYY',
          type: 'year',
          'disabled-date': time => {
            return dayjs(time.getTime()) > dayjs();
          },
        },
      },
      ...map(commonFieldList, v => ({
        ...v,
        eventHandle: {
          input: val => getInputVal(val, formOpts, v.value),
        },
      })),
    ],
    rules: {
      year: [{ required: true, message: '请选择年份', trigger: 'blur' }],
      month1: commonRule,
      month2: commonRule,
      month3: commonRule,
      month4: commonRule,
      month5: commonRule,
      month6: commonRule,
      month7: commonRule,
      month8: commonRule,
      month9: commonRule,
      month10: commonRule,
      month11: commonRule,
      month12: commonRule,
    },
  });
  const total = ref('-');

  const openRun = () => {
    run({ year: formOpts.formData.year });
  };
  const [, , run] = useRequest(getCEQuota, {
    manual: true,
    onSuccess: res => {
      formOpts.formData = omit(res.data, ['total']);
      total.value = res.data.total;
    },
  });
  useWatch(
    () => formOpts.formData,
    n => {
      const bool = every(n, v => !isNil(v));
      total.value = bool ? sum(values(omit(n, 'year'))).toFixed(2) : '-';
    },
    { deep: true },
  );

  return [TFormQuota, formOpts, total, openRun];
};
